package com.shugl.demo.utils;

import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Http工具类
 */
public class HttpContextUtils {


    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }

        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        Enumeration<String> parameters = request.getParameterNames();

        Map<String, String> params = new HashMap<>();
        while (parameters.hasMoreElements()) {
            String parameter = parameters.nextElement();
            String value = request.getParameter(parameter);
//            if (StringUtils.isNotBlank(value)) {
//                params.put(parameter, value);
//            }
        }

        return params;
    }

    public static String getLanguage() {
        //默认语言
        String defaultLanguage = "zh-CN";
        //request
//        HttpServletRequest request = getHttpServletRequest();
//        if (request == null) {
//            return defaultLanguage;
//        }
//        //请求语言
//        String reqLanguage = request.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
//        defaultLanguage = StringUtils.isBlank(reqLanguage) ? defaultLanguage : reqLanguage;
        return defaultLanguage;
    }


    /**
     * 获取请求真实IP地址
     *
     * @return IP地址
     */
    public static String getCurrentRealIp() {
        HttpServletRequest request = getHttpServletRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        return getRealIp(request);
    }

    /**
     * 获取请求真实IP地址
     *
     * @param request HttpServletRequest
     * @return IP地址
     */
    public static String getRealIp(HttpServletRequest request) {
        // 这个一般是Nginx反向代理设置的参数
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多IP的情况（只取第一个IP）
        if (ip != null && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            ip = ipArray[0];
        }
        return ip;
    }

    /**
     * 获取请求Header
     *
     * @param request HttpServletRequest
     * @return Header参数
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    public static HttpServletRequest setContentType() {
        //request
        HttpServletRequest request = getHttpServletRequest();
        if (request != null) {
            Class<? extends HttpServletRequest> requestClass = request.getClass();
            try {
                Field request1 = requestClass.getDeclaredField("request");
                request1.setAccessible(true);
                Object o = request1.get(request);
                Field coyoteRequest = o.getClass().getDeclaredField("coyoteRequest");
                coyoteRequest.setAccessible(true);
                Object o1 = coyoteRequest.get(o);
                System.out.println("coyoteRequest实现类=" + o1.getClass().getName());
                Field headers = o1.getClass().getDeclaredField("headers");
                headers.setAccessible(true);
                MimeHeaders o2 = (MimeHeaders) headers.get(o1);
                o2.removeHeader("content-type");
                o2.removeHeader("Content-Type");
                o2.addValue("content-type").setString("application/json;charset=UTF-8");
                o2.addValue("Content-Type").setString("application/json;charset=UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return request;
    }

}
